﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using ElingOA6_Admin_DSJCJ.Common;
using ElingOA6_Admin_DSJCJ.Models;
using DevExpress.Web.Mvc;

namespace ElingOA6_Admin_DSJCJ.Areas.Admin.Controllers
{
    /// <summary>
    /// 用户组管理
    /// </summary>
    [OutputCache(Duration = 0, VaryByParam = "none")]
    public class EmplGroupController : AdminBaseController
    {
        private BLL.PrvGroup prvGroupBLL = new BLL.PrvGroup();
        private BLL.HRDept hrDeptBLL = new BLL.HRDept();
        private BLL.PrvUser prvUserBLL = new BLL.PrvUser();
        /// <summary>
        /// 用户组管理
        /// </summary>
        /// <param name="focusNodeName">选中节点</param>
        /// <returns>用户组管理主页面</returns>
        [AuthorityActionFilter("m_PrvGroup", Order = 1)]
        [LogPageActionFilter("用户组管理", Order = 2)]
        public ActionResult Index(string focusNodeName = "")
        {
            ViewData["focusNodeName"] = focusNodeName;
            BLL.PrvGroup groupBLL = new BLL.PrvGroup();
            string where = " FEntityNo='" + GlobalConstant.ENTITYNO + "'";
            List<Model.PrvGroup> prvGroupList = groupBLL.GetModelList(where);
            ViewData["isHaveTreeData"] = prvGroupList.Count == 0 ? false : true;
            return View();
        }

        /// <summary>
        /// 左边用户组树
        /// </summary>
        /// <param name="focusNodeName">选中节点</param>
        /// <returns>返回左边用户树视图</returns>
        public ActionResult GroupTree(string focusNodeName = "")
        {
            BLL.PrvGroup groupBLL = new BLL.PrvGroup();
            string where = " FEntityNo='" + GlobalConstant.ENTITYNO + "'";
            List<Model.PrvGroup> prvGroupList = groupBLL.GetModelList(where);
            ElingOA6_Admin_DSJCJ.Models.TreeModelList treeModelList = new TreeModelList();
            if (prvGroupList.Count > 0)
            {
                foreach (Model.PrvGroup grpModel in prvGroupList)
                {
                    TreeItemModel treeParentItemModel = new TreeItemModel(null)
                    {
                        Id = DevExpressHelper.GetUrl(new { Controller = "EmplGroup", Action = "EditGroup" }) + "|" + grpModel.FGroupNo,
                        Name = grpModel.FGroupName,
                        ImageUrl = Url.Content("~/Content/ControlImages/user_group.png")
                    };
                    treeModelList.Add(treeParentItemModel);
                }
            }
            ViewData["focusNodeName"] = focusNodeName;
            return View(treeModelList);
        }
        /// <summary>
        /// 修改用户组
        /// </summary>
        /// <param name="groupID">用户组编号</param>
        /// <returns>返回修改用户组视图</returns>
        public ActionResult EditGroup(string groupID)
        {
            return EditGroup(groupID, "", "EDIT", null);
        }
        /// <summary>
        /// 增加用户组
        /// </summary>
        /// <returns>返回增加用户组视图</returns>
        public ActionResult AddGroup()
        {
            //return AddGroup("", null);
            return EditGroup("0", "", "ADD_SAME", new Model.PrvGroup());
        }

        /// <summary>
        /// 保存
        /// </summary>
        /// <param name="prvGroupModel">用户组信息</param>
        /// <returns>返回用户组保存后视图</returns>
        public ActionResult Save(Model.PrvGroup prvGroupModel)
        {
            bool isSuccess = true;
            string errorMessage = "";
            ActionResult actionResult = null;
            //model赋值
            //Model.PrvGroup prvGroupModel = new Model.PrvGroup()
            //{
            //    FGroupName = Fetch.Post("txtFGroupName"),
            //    FNote = Fetch.Post("txtFNote")
            //};
            string groupID = "0";
            if (Fetch.Post("hdGroupID") != "0")
            {
                prvGroupModel.FGroupNo = Fetch.Post("hdGroupID");
            }
            //数据逻辑验证
            if (prvGroupModel.FGroupName == "")
            {
                errorMessage = "用户组不能为空";
                isSuccess = false;
            }
            prvGroupModel.FEntityNo = GlobalConstant.ENTITYNO;
            BLL.PrvGroup groupBLL = new BLL.PrvGroup();
            string funcs = Fetch.Post("hdFunctionSelect");
            List<string> userFuncList = new List<string>();
            if (funcs != "")
            {
                userFuncList = funcs.Split(new char[1] { ',' }).ToList();
            }

            string users = Fetch.Post("hdOrgUserSelect");
            List<string> orgUserList = new List<string>();
            if (users != "")
            {
                orgUserList = users.Split(new char[1] { ',' }).ToList();
            }
            switch (Fetch.Post("hdMethod"))
            {
                case "ADD_SAME":
                    {
                        if (groupBLL.Exists(prvGroupModel.FGroupNo, prvGroupModel.FEntityNo))
                        {
                            errorMessage = "用户组编号已存在";
                            isSuccess = false;
                        }
                        else
                        {
                            try
                            {
                                groupID = groupBLL.AddPrvGroup(prvGroupModel, userFuncList, orgUserList);
                                //增加成功
                                ViewData["focusKey"] = DevExpressHelper.GetUrl(new { Controller = "EmplGroup", Action = "EditGroup" }) + "|" + groupID;//焦点定位的节点ID
                                ViewData["methodFromType"] = Fetch.Post("hdMethod");
                                ViewData["nodeText"] = prvGroupModel.FGroupName;
                                actionResult = View("SuccessMessageByTree");
                            }
                            catch
                            {
                                errorMessage = "操作异常:";
                            }


                        }
                        if (actionResult == null)
                        {
                            actionResult = EditGroup("0", errorMessage, Fetch.Post("hdMethod"), new Model.PrvGroup());
                        }
                        break;
                    }
                case "EDIT":
                    {
                        if (isSuccess)
                        {
                            try
                            {
                                groupBLL.EditPrvGroup(prvGroupModel, userFuncList, orgUserList);
                                //修改成功
                                ViewData["RedirectURL"] = Url.Action("EditGroup", "EmplGroup", new { groupID = prvGroupModel.FGroupNo });
                                ViewData["methodFromType"] = Fetch.Post("hdMethod");
                                ViewData["nodeText"] = prvGroupModel.FGroupName;
                                actionResult = View("SuccessMessageByTree");
                            }
                            catch
                            {
                                errorMessage = "操作异常:";
                            }
                        }
                        if (actionResult == null)
                        {
                            actionResult = EditGroup(prvGroupModel.FGroupNo, errorMessage, Fetch.Post("hdMethod"), prvGroupModel);
                        }
                        break;
                    }
            }

            return actionResult;
        }
        /// <summary>
        /// 删除用户组
        /// </summary>
        /// <param name="groupIDEn">用户组编号 （加密）</param>
        /// <returns>删除后所显示信息</returns>
        [HttpPost]
        public string DeleteGroup(string groupIDEn)
        {
            string jsonstr = "FAILED";
            string errorMessage = "错误";
            string groupID = "0";
            if (groupIDEn != "")
            {
                try
                {
                    groupID = GenerateUtil.Decrypt(groupIDEn, "FGroupNo");
                    try
                    {
                        BLL.PrvGroup groupBLL = new BLL.PrvGroup();
                        groupBLL.DeleteGroup(groupID, GlobalConstant.ENTITYNO);
                        jsonstr = "SUCCESS";
                    }
                    catch
                    {
                        errorMessage = "操作异常";
                    }
                }
                catch
                {
                    errorMessage = "参数错误";
                }

                if (jsonstr == "FAILED")
                {
                    jsonstr += "FAILED|" + errorMessage;
                }
            }
            return jsonstr;
        }
        /// <summary>
        /// 获取特定菜单有权限的用户树
        /// </summary>
        /// <param name="functionNo"></param>
        /// <returns></returns>
        public string GetFunctionUser(string functionNo)
        {
            List<string> loginIDList = new List<string>();
            loginIDList = prvGroupBLL.GetLoginIDListByFunctionNo(functionNo, GlobalConstant.ENTITYNO); //当前用户组的所有成员
            List<Model.HRDept> hrDeptList = hrDeptBLL.GetListNoNameByEntityNo(GlobalConstant.ENTITYNO);
            string treeJsonStr = "";
            //获取组织用户树
            if (hrDeptList.Count > 0)
            {
                treeJsonStr += "[";
                List<Model.HRDept> orgFirstList = (from m in hrDeptList
                                                   where m.FParentDeptNo == null
                                                   select m).ToList();
                foreach (Model.HRDept orgModel in orgFirstList)
                {
                    //获取当前部门及其子部门的人员
                    List<Model.PrvUser> prvUserCTEList = prvUserBLL.GetPrvUserListByDeptNoCTE(orgModel.FDeptNo, GlobalConstant.ENTITYNO);
                    //当前部门及其子部门有权限的人员
                    List<Model.PrvUser> tmpUserCTEList = (from c in prvUserCTEList
                                                          where loginIDList.Contains(c.FLogID)
                                                          select c).ToList();

                    //当前部门的人员
                    List<Model.PrvUser> tmpUserList = (from c in tmpUserCTEList
                                                       where c.FDeptNo == orgModel.FDeptNo
                                                       select c).ToList();
                    tmpUserList = tmpUserList.OrderBy(s => s.FSeq).ToList();

                    //子部门
                    List<Model.HRDept> tmpModelList = (from m in hrDeptList
                                                       where m.FParentDeptNo == orgModel.FDeptNo
                                                       select m).OrderBy(s => s.FDeptNo).OrderBy(s => s.FSeq).ToList();


                    if (tmpUserCTEList.Count > 0)//如果当前部门及其子部门含有 ‘权限人员’，则增加
                    {
                        treeJsonStr += "{'title':'" + orgModel.FDeptShorName + "','key':'" + orgModel.FDeptNo + "','isFolder':true,'expand':false";
                        treeJsonStr += ",'children':[";
                        foreach (Model.PrvUser userModel in tmpUserList)
                        {
                            treeJsonStr += "{'title':'" + userModel.FUserName + "','key':'" + userModel.FLogID + "'";
                            treeJsonStr += "},";
                        }

                        GetChildOrgFunctionUserList(tmpModelList, ref treeJsonStr, hrDeptList, loginIDList);

                        treeJsonStr = treeJsonStr.TrimEnd(',');
                        treeJsonStr += "]";
                        treeJsonStr += "},";
                    }


                }
                treeJsonStr = treeJsonStr.TrimEnd(',');
                treeJsonStr += "]";
                treeJsonStr = treeJsonStr.Replace("\\", "");
                treeJsonStr = treeJsonStr.Replace("'", "\"");
                return treeJsonStr;
            }
            else
            {
                return "";
            }
        }


        #region 私有方法
        /// <summary>
        /// 修改用户组
        /// </summary>
        /// <param name="groupID">用户组编号</param>
        /// <param name="jsAlert">显示文字</param>
        /// <param name="methodType">页面类型  ADD_SAME 新增; EDIT 修改</param>
        /// <param name="prvGroupModel">用户组数据</param>
        /// <returns>返回增加或修改用户组视图</returns>
        private ActionResult EditGroup(string groupID, string jsAlert, string methodType, Model.PrvGroup prvGroupModel)
        {
            BLL.PrvGroup groupBLL = new BLL.PrvGroup();
            BLL.PrvUserGroup prvUserGroupBLL = new BLL.PrvUserGroup();
            BLL.PrvUser prvprvUserBLL = new BLL.PrvUser();
            BLL.Index prvfunBll = new BLL.Index();
            //增加和修改同一个页面
            ViewData["hdMethod"] = methodType;//类型  ADD_SAME 新增; EDIT 修改
            if (prvGroupModel == null)
            {
                prvGroupModel = groupBLL.GetModel(groupID, GlobalConstant.ENTITYNO);
            }
            if (prvGroupModel != null)
            {
                
                List<string> loginIDList = new List<string>();
                if (methodType == "EDIT")
                {
                    prvGroupModel.FGroupIDEn = GenerateUtil.Encrypt(prvGroupModel.FGroupNo.ToString(), "FGroupNo");
                    loginIDList = prvGroupBLL.GetLoginIDListByGroupID(groupID, GlobalConstant.ENTITYNO); //当前用户组的所有成员
                }
                List<Model.HRDept> hrDeptList = hrDeptBLL.GetListNoNameByEntityNo(GlobalConstant.ENTITYNO);
                string treeJsonStr = "";
                //获取组织用户树
                if (hrDeptList.Count > 0)
                {
                    treeJsonStr += "[";
                    List<Model.HRDept> orgFirstList = (from m in hrDeptList
                                                         where m.FParentDeptNo == null
                                                         select m).ToList();
                    foreach (Model.HRDept orgModel in orgFirstList)
                    {
                        treeJsonStr += "{'title':'" + orgModel.FDeptShorName + "','key':'" + orgModel.FDeptNo + "','isFolder':true,'expand':false";
                        List<Model.HRDept> tmpModelList = (from m in hrDeptList
                                                           where m.FParentDeptNo == orgModel.FDeptNo
                                                           select m).OrderBy(s => s.FDeptNo).OrderBy(s => s.FSeq).ToList();
                        //获取人员
                        List<Model.PrvUser> prvUserList = prvUserBLL.GetPrvUserListByDeptNo(orgModel.FDeptNo,GlobalConstant.ENTITYNO);
                        prvUserList = prvUserList.OrderBy(s => s.FSeq).ToList();
                        if (tmpModelList.Count > 0 || prvUserList.Count > 0)
                        {
                            treeJsonStr += ",'children':[";
                            foreach (Model.PrvUser userModel in prvUserList)
                            {
                                treeJsonStr += "{'title':'" + userModel.FUserName + "','key':'" + userModel.FLogID + "'";
                                if (loginIDList.Contains(userModel.FLogID))
                                {
                                    treeJsonStr += ",'select':true";
                                }
                                treeJsonStr += "},";
                            }

                            GetChildOrgList(tmpModelList, ref treeJsonStr, hrDeptList, loginIDList);
                            treeJsonStr += "]";
                        }
                        treeJsonStr += "},";
                    }
                    treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
                    treeJsonStr += "]";
                    treeJsonStr = treeJsonStr.Replace("\\", "");
                    treeJsonStr = treeJsonStr.Replace("'", "\"");
                }
                ViewData["treeJsonStrOrgUser"] = treeJsonStr;


                //获取用户权限树
                treeJsonStr = "";
                List<string> functionNOList = new List<string>();
                if (methodType == "EDIT")
                {
                    functionNOList = prvGroupBLL.GetFunctionNOListByGroupID(groupID, GlobalConstant.ENTITYNO);//该用户组的权限列表
                }
                List<Model.PrvFunctList> prvFunctListList =prvfunBll.GetPrvFunctList();
                treeJsonStr = "";
                if (prvFunctListList.Count > 0)
                {

                    treeJsonStr += "[";
                    List<Model.PrvFunctList> prvFirstList = (from m in prvFunctListList
                                                             where m.FPreFunctNo == "m_PrvFunctList"
                                                             orderby m.Fsort
                                                             select m).ToList();
                    foreach (Model.PrvFunctList prvModel in prvFirstList)
                    {
                        treeJsonStr += "{'title':'" + prvModel.FfunctName + "','key':'" + prvModel.FFunctNo + "','expand':true,'icon':'" + (prvModel.FPictName.Trim() != "" ? Url.Content(prvModel.FPictName) : "" )+ "'";
                        List<Model.PrvFunctList> tmpModelList = (from m in prvFunctListList
                                                                 where m.FPreFunctNo == prvModel.FFunctNo
                                                                 orderby m.Fsort
                                                                 select m).ToList();
                        if (functionNOList.Contains(prvModel.FFunctNo))
                        {
                            treeJsonStr += ",'select':true";
                        }
                        if (tmpModelList.Count > 0)
                        {
                            treeJsonStr += ",'children':[";

                            GetChildFuncList(tmpModelList, ref treeJsonStr, prvFunctListList, functionNOList);
                            treeJsonStr += "]";
                        }
                        else
                        {
                            treeJsonStr += ",'href':'" + Url.Action("Index", prvModel.FfunctURL) + "','target':'content'";
                        }
                        treeJsonStr += "},";
                    }
                    treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));
                    treeJsonStr += "]";
                    treeJsonStr = treeJsonStr.Replace("\\", "");
                    treeJsonStr = treeJsonStr.Replace("'", "\"");
                }
                ViewData["treeJsonStrUserFunc"] = treeJsonStr;
                //隐藏字段

                ViewData["jsAlert"] = jsAlert;
                ViewData["groupID"] = groupID;

                return View("EditGroup", prvGroupModel);
            }
            return null;
        }



        /// <summary>
        /// 递归获取组织用户树形菜单
        /// </summary>
        /// <param name="prvChildList"></param>
        /// <param name="treeJsonStr"></param>
        private void GetChildOrgList(List<Model.HRDept> orgChildList, ref string treeJsonStr, List<Model.HRDept> HRDeptList, List<string> loginIDList)
        {

            foreach (Model.HRDept orgModel in orgChildList)
            {
                treeJsonStr += "{'title':'" + orgModel.FDeptShorName + "','key':'" + orgModel.FDeptNo + "','isFolder':true";
                List<Model.HRDept> tmpModelList = (from m in HRDeptList
                                                     where m.FParentDeptNo == orgModel.FDeptNo
                                                     select m).ToList();


                //获取人员
                List<Model.PrvUser> prvUserList = prvUserBLL.GetPrvUserListByDeptNo(orgModel.FDeptNo,GlobalConstant.ENTITYNO);
                if (tmpModelList.Count > 0 || prvUserList.Count > 0)
                {

                    treeJsonStr += ",'children':[";
                    foreach (Model.PrvUser userModel in prvUserList)
                    {
                        treeJsonStr += "{'title':'" + userModel.FUserName + "','key':'" + userModel.FLogID + "'";
                        if (loginIDList.Contains(userModel.FLogID))
                        {
                            treeJsonStr += ",'select':true";
                        }
                        treeJsonStr += "},";
                    }
                    GetChildOrgList(tmpModelList, ref treeJsonStr, HRDeptList, loginIDList);
                    treeJsonStr += "]";
                }

                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));

        }
        /// <summary>
        /// 递归获取组织菜单权限的用户树形菜单
        /// </summary>
        /// <param name="prvChildList"></param>
        /// <param name="treeJsonStr"></param>



        /// <summary>
        /// 递归获取组织菜单权限的用户树形菜单
        /// </summary>
        /// <param name="prvChildList"></param>
        /// <param name="treeJsonStr"></param>
        private void GetChildOrgFunctionUserList(List<Model.HRDept> orgChildList, ref string treeJsonStr, List<Model.HRDept> HRDeptList, List<string> loginIDList)
        {

            foreach (Model.HRDept orgModel in orgChildList)
            {
                //获取当前部门及其子部门的人员
                List<Model.PrvUser> prvUserCTEList = prvUserBLL.GetPrvUserListByDeptNoCTE(orgModel.FDeptNo, GlobalConstant.ENTITYNO);
                //当前部门及其子部门有权限的人员
                List<Model.PrvUser> tmpUserCTEList = (from c in prvUserCTEList
                                                      where loginIDList.Contains(c.FLogID)
                                                      select c).ToList();

                //子部门
                List<Model.HRDept> tmpModelList = (from m in HRDeptList
                                                   where m.FParentDeptNo == orgModel.FDeptNo
                                                   select m).ToList();
                //当前部门的人员
                List<Model.PrvUser> tmpUserList = (from c in tmpUserCTEList
                                                   where c.FDeptNo == orgModel.FDeptNo
                                                   select c).ToList();
                tmpUserList = tmpUserList.OrderBy(s => s.FSeq).ToList();

                if (tmpUserCTEList.Count > 0)//如果当前部门及其子部门含有 ‘权限人员’，则增加
                {
                    treeJsonStr += "{'title':'" + orgModel.FDeptShorName + "','key':'" + orgModel.FDeptNo + "','isFolder':true";
                    treeJsonStr += ",'children':[";
                    foreach (Model.PrvUser userModel in tmpUserList)
                    {
                        treeJsonStr += "{'title':'" + userModel.FUserName + "','key':'" + userModel.FLogID + "'";
                        treeJsonStr += "},";
                    }
                    GetChildOrgList(tmpModelList, ref treeJsonStr, HRDeptList, loginIDList);

                    treeJsonStr = treeJsonStr.TrimEnd(',');
                    treeJsonStr += "]";
                    treeJsonStr += "},";
                }
            }
        }
        /// <summary>
        /// 递归获取权限树形菜单
        /// </summary>
        /// <param name="prvChildList"></param>
        /// <param name="treeJsonStr"></param>
        private void GetChildFuncList(List<Model.PrvFunctList> prvChildList, ref string treeJsonStr, List<Model.PrvFunctList> prvFunctListList, List<string> functionNOList)
        {
            foreach (Model.PrvFunctList prvModel in prvChildList)
            {
                treeJsonStr += "{'title':'" + prvModel.FfunctName + "','key':'" + prvModel.FFunctNo + "','expand':true,'icon':'" + (prvModel.FPictName.Trim() != "" ? Url.Content(prvModel.FPictName):"") + "'";
                List<Model.PrvFunctList> tmpModelList = (from m in prvFunctListList
                                                         where m.FPreFunctNo == prvModel.FFunctNo
                                                         orderby m.Fsort
                                                         select m).ToList();
                if (functionNOList.Contains(prvModel.FFunctNo))
                {
                    treeJsonStr += ",'select':true";
                }
                if (tmpModelList.Count > 0)
                {
                    treeJsonStr += ",'children':[";
                    GetChildFuncList(tmpModelList, ref treeJsonStr, prvFunctListList, functionNOList);
                    treeJsonStr += "]";
                }
                treeJsonStr += "},";
            }
            treeJsonStr = treeJsonStr.Substring(0, treeJsonStr.LastIndexOf(","));

        }

        #endregion
    }
}
